package com.forever7776.life.web.controller.life.m;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.forever7776.life.core.common.vo.UserBlogSearchVO;
import com.forever7776.life.core.entity.blog.Blog;
import com.forever7776.life.core.entity.blog.BlogExt;
import com.forever7776.life.core.entity.stat.StatBlog;
import com.forever7776.life.core.service.blog.IBlogExtService;
import com.forever7776.life.core.service.blog.IBlogService;
import com.forever7776.life.core.service.blog.IBlogTypeService;
import com.forever7776.life.core.service.stat.IStatBlogService;
import com.forever7776.life.remote.common.enums.StatusEnum;
import com.forever7776.life.remote.common.vo.ResultVO;
import com.forever7776.life.web.controller.BaseController;
import enums.ResultEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import util.ResultUtil;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;


/**
 * 我的博客
 *
 * @author kz
 * @date 2018年02月10日
 */
@Controller
@RequestMapping(value = "/m/blog")
public class MyBlogController extends BaseController {

    @Autowired
    private IBlogService iBlogService;

    @Autowired
    private IBlogExtService iBlogExtService;

    @Autowired
    private IBlogTypeService iBlogTypeService;

    @Autowired
    private IStatBlogService iStatBlogService;

    /**
     * 我的博客页面
     *
     * @return
     */
    @RequestMapping
    public String index() {
        return USER_VIEW_PAGE_PATH + "blog/index";
    }

    /**
     * 博客列表
     *
     * @param searchVO
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public JSONObject list(UserBlogSearchVO searchVO) {
        JSONObject result = new JSONObject();
        searchVO.setUserId(getUserId());
        Page<Blog> page = iBlogService.selectAll(new Page<Blog>(pageNumber, pageSize), searchVO);
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<Integer> thirdIds = new LinkedList<>();
            for (Blog b : page.getRecords()) {
                thirdIds.add(b.getId());
            }
            Map<Integer, StatBlog> map = iStatBlogService.selectBlogIdMap(thirdIds);
            result.put("map", map);
        }
        result.put("page", page);
        return result;
    }

    /**
     * 编辑博客
     *
     * @param id
     * @return
     */
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, ModelMap modelMap) {
        String userId = getUserId();
        Blog blog = iBlogService.selectByUserId(userId, id);
        if (blog == null) {
            return "redirect:/404";
        }
        BlogExt blogExt = iBlogExtService.selectByBlogId(id);
        modelMap.put("types", iBlogTypeService.selectAll(StatusEnum.NORMAL.getKey()));
        modelMap.put("blog", blog);
        modelMap.put("blogExt", blogExt);
        return USER_VIEW_PAGE_PATH + "blog/edit";
    }

    /**
     * 保存修改博客
     *
     * @param blog
     * @param blogExt
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject edit(@PathVariable Integer id, Blog blog, BlogExt blogExt) {
        if (iBlogService.selectByUserId(getUserId(), id) == null) {
            return ResultUtil.getFailResult("该博客不存在!");
        }
        JSONObject result = checkBlog(blog, blogExt);
        if (result.get("code").equals(ResultEnum.STATUS.FAIL.getCode())) {
            return result;
        }
        blog.setBlogTypeId(StringUtils.join(JSONObject.parseArray(blog.getBlogTypeId()), ","));
        blog.setUserId(getUserId());
        iBlogService.edit(blog, blogExt);
        return result;
    }


    /**
     * 删除博客
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO delete(@PathVariable Integer id) {
        return iBlogService.delete(id);
    }


    /**
     * 查询博客数量
     *
     * @return
     */
    @RequestMapping(value = "/count", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject count() {
        JSONObject result = new JSONObject();
        result.put("count", iBlogService.selectCount(getUserId()));
        return result;
    }

    /**
     * 创建博客页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap modelMap) {
        modelMap.put("types", iBlogTypeService.selectAll(StatusEnum.NORMAL.getKey()));
        return USER_VIEW_PAGE_PATH + "blog/add";
    }

    /**
     * 创建博客
     *
     * @param blog
     * @param blogExt
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject add(Blog blog, BlogExt blogExt) {
        JSONObject result = checkBlog(blog, blogExt);
        if (result.get("code").equals(ResultEnum.STATUS.FAIL.getCode())) {
            return result;
        }
        blog.setUserId(getUserId());
        blog.setBlogTypeId(StringUtils.join(JSONObject.parseArray(blog.getBlogTypeId()), ","));
        iBlogService.save(blog, blogExt);
        return result;
    }

    /**
     * 修改博客是否开放状态
     *
     * @param blogId
     * @param openup
     */
    @RequestMapping(value = "/openup/{blogId}", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateOpenUp(@PathVariable Integer blogId, @RequestParam(value = "openup", defaultValue = "1") Integer openup) {
        String userId = getUserId();
        iBlogService.updateOpenUp(userId, blogId, openup);
        return ResultUtil.getSuccessResult(openup == 0 ? "私密成功~~" : "开放成功~~");
    }

    /**
     * 新增blog表单校验
     *
     * @param blog
     * @param blogExt
     * @return
     */
    public JSONObject checkBlog(Blog blog, BlogExt blogExt) {
        if (StringUtils.isEmpty(blog.getTitle())) {
            return ResultUtil.getFailResult("标题不能为空~~~");
        }
        if (StringUtils.isEmpty(blogExt.getContent())) {
            return ResultUtil.getFailResult("内容不能为空~~~");
        }
        if (JSONObject.parseArray(blog.getBlogTypeId()).size() == 0) {
            return ResultUtil.getFailResult("请至少选择一个分类~~~");
        }
        return ResultUtil.getSuccessResult("");


    }


}
